package com.wangzhy.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 负责下载图片的任务，可以由线程执行 （Runnable）
 *
 *
 *
 */
@Slf4j
public class DownloadTask implements Runnable {

	String url;
	String path;

	public DownloadTask(String url, String path) {
		super();
		this.url = url;
		this.path = path;
	}
	/**
	 * 根据图片网络地址下载图片
	 */
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
		File file = null;
		File dirFile = null;
		FileOutputStream fos = null;

		HttpURLConnection httpCon = null;
		URLConnection con = null;
		URL urlObj = null;
		InputStream in = null;
		byte[] size = new byte[1024];
		int num = 0;
		try {
//			log.info("start download ======url ==="+url+",path=====>"+path);
			String downloadName = url.substring(url.lastIndexOf("/") + 1);
			dirFile = new File(path);
			if (!dirFile.exists() && path.length() > 0) {
				FileUtil.createDir(path);
			}
			file = new File(path +File.separator+ downloadName);
			fos = new FileOutputStream(file);
			if (url.startsWith("http")) {
				urlObj = new URL(url);
				con = urlObj.openConnection();
				httpCon = (HttpURLConnection) con;
				in = httpCon.getInputStream();
				while ((num = in.read(size)) != -1) {
					for (int i = 0; i < num; i++){
						fos.write(size[i]);
					}
				}
				log.info(" 下载成功 ,url= "+url+",path="+path);
			}
		} catch (FileNotFoundException notFoundE) {
			System.out.println("找不到该网络图片....");
		} catch (NullPointerException nullPointerE) {
			System.out.println("找不到该网络图片....");
		} catch (IOException ioE) {
			System.out.println("产生IO异常.....");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
//			log.info("关闭连接.....");
			try {
				// 不论是否发生异常都会执行的
				if (fos != null) {
					fos.close();
				}
				if (con != null) {
					httpCon.disconnect();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
